package org.itboys.core.service.mongo.web;

import org.itboys.commons.ErrorException;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.tray.SundayTrayMapper;
import org.itboys.core.dto.tray.SundayTrayApplyDto;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.entity.mongo.SundayStore;
import org.itboys.core.entity.mongo.SundayTrayApply;
import org.itboys.core.entity.mysql.tray.SundayTray;
import org.itboys.core.entity.mysql.tray.SundayTrayModel;
import org.itboys.core.service.mysql.web.SundayTrayModelService;
import org.itboys.core.util.ZXingCode;
import org.itboys.core.util.ZipUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作者：zzq
 * 时间：2018/12/5
 * 描述：托盘申请
 */
@Service
public class SundayTrayApplyService extends BaseMongoService<SundayTrayApply> {
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayTrayModelService modelService;
    @Autowired
    private SundayStoreService storeService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayTrayMapper trayMapper;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayTrayApply> getEntityClass() {
        return SundayTrayApply.class;
    }

    /**
     * 审核
     * @param applyId
     * @param status
     */
    @Transactional
    public void handle(Long applyId, Integer status,Long startId,Long endId) {
        SundayTrayApply apply = super.getById(applyId);
        if(status==SundayCommonConstants.tray_apply_status_ytg){
            //分配托盘
            Long cha=endId-startId+1;
            if(cha.longValue()!=apply.getNum().longValue()){
                throw new ErrorException(ExceptionEnum.TRAY_APPLY_NUM_EXCEPTION.getValue());
            }
            List<Long> trayIds=new ArrayList<>();
            for(int i=startId.intValue();i<=endId.longValue();i++){
                trayIds.add(Long.valueOf(i));
            }
            Map<String,Object> param=new HashMap<String,Object>();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("ids",trayIds);
            List<SundayTray> trays=trayMapper.select(param);
            List<File> srcFiles = new ArrayList<>();
            Long random = Long.valueOf(System.currentTimeMillis());
            for (SundayTray tray :trays) {
                if(tray.getStatus()!=SundayCommonConstants.tray_status_dfp){
                    throw new ErrorException(ExceptionEnum.TRAY_STATUS_EXCEPTION.getValue());
                }
                if(tray.getModelId().longValue()!=apply.getModelId().longValue()){
                    throw new ErrorException(ExceptionEnum.TRAY_MODEL_EXCEPTION.getValue());
                }
                srcFiles.add(new File(resourceHolder.getStringValue("fileUploadPath")+tray.getEwm()));
            }
            String zipPath="/ewmZip/"+random+".zip";
            ZipUtils.zipFiles(srcFiles,new File(resourceHolder.getStringValue("fileUploadPath")+zipPath));
            apply.setZipPath(zipPath);
            //批量修改托盘状态
            param.clear();
            param.put("status", SundayCommonConstants.tray_status_dzl);
            param.put("serviceId", apply.getMemberId());
            param.put("applyId", applyId);
            param.put("ownerId", apply.getMemberId());
            param.put("storeId", apply.getStoreId());
            trayMapper.batchUpdateFields(param, trayIds);
        }

        apply.setStatus(status);
        super.updateExceptEmpty(applyId, apply);
    }


    public PageResult<SundayTrayApplyDto> select(HttpServletRequest request) {
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request, "memberId");
        param.put("isDeleted", 0);
        Map<String, String> containsparam = ParamUtil.packageMongoVagueParam(request, "");
        PageResult<SundayTrayApply> applys = super.containpageQuery(request, containsparam, param);
        PageResult<SundayTrayApplyDto> result = new PageResult<>(packageMultiDto(applys.getData()), applys.getTotal());
        return result;
    }


    /**
     * 组装多个
     *
     * @param applys
     * @return
     */
    public List<SundayTrayApplyDto> packageMultiDto(List<SundayTrayApply> applys) {
        List<SundayTrayApplyDto> dtos = new ArrayList<>();
        List<Long> memberIds = applys.stream().map(e -> e.getMemberId()).collect(Collectors.toList());
        List<Long> modelIds = applys.stream().map(e -> e.getModelId()).collect(Collectors.toList());
        List<Long> storeIds = applys.stream().map(e -> e.getStoreId()).collect(Collectors.toList());
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("id in", memberIds);
        List<SundayMember> members = memberService.list(param);
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("ids", modelIds);
        List<SundayTrayModel> models = modelService.select(param);
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("id in", storeIds);
        List<SundayStore> stores = storeService.list(param);

        for (SundayTrayApply apply : applys) {
            SundayTrayApplyDto dto = new SundayTrayApplyDto();
            BeanUtils.copyProperties(apply, dto);
            for (SundayMember member : members) {
                if (apply.getMemberId().longValue() == member.getId()) {
                    dto.setMemberName(member.getNickName());
                    break;
                }
            }
            for (SundayTrayModel model : models) {
                if (apply.getModelId().longValue() == model.getId().longValue()) {
                    dto.setModelName(model.getName());
                    break;
                }
            }
            for (SundayStore store : stores) {
                if (apply.getStoreId()!=null&&apply.getStoreId().longValue() == store.getId()) {
                    dto.setStoreName(store.getName());
                    break;
                }
            }
            dtos.add(dto);
        }
        return dtos;
    }


}
